//
//  ShopViewController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/27.
//

#import "ShopViewController.h"
#import "SearchView.h"
#import "ShopInfoView.h"
#import <JXCategoryView/JXCategoryView.h>
#import "ShopListController.h"
#import "PublishShopViewController.h"
#import "FollowTipsView.h"
#import "ScanCodeViewController.h"
#import "FollowSetView.h"

@interface ShopViewController ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate>

@property (nonatomic, strong) SearchView *searchV;
@property (nonatomic, strong) ShopInfoView *headerView;
@property (nonatomic, strong) JXCategoryTitleView *categoryV;
@property (nonatomic, strong) JXCategoryListContainerView *containView;
@property (nonatomic, strong) UserModel *model;
@property (nonatomic, strong) UIButton *manageShop;

@end

@implementation ShopViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getUserInfoData];
}
- (void)initDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitManager) name:@"exitManager" object:nil];
    
    [UIViewController removeControllerWithString:@"ScanCodeViewController"];
    self.hbd_barAlpha = 0;
    if (self.userId.length <= 0) {
        self.userId = kUserAccount.user.id;
    }
    if (self.isPush) {
        self.navigationTitle = @"店铺详情";
    }
    if (self.isPush && ![self isSelef]) {
        UIBarButtonItem *more = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreAction)];
        self.navigationItem.rightBarButtonItem = more;
    }
}
- (void)initViews {
    [self.view addSubview:self.searchV];
    [self.view addSubview:self.headerView];
    
    UIView *contentBg = [[UIView alloc] initWithFrame:CGRectMake(0, (self.isPush ? kHeightForNaigation : kHeightForStatusBar) + 56 +140, kWidthForScreen, kHeightForScreen-((self.isPush ? kHeightForNaigation : kHeightForStatusBar) + 56 +140))];
    contentBg.backgroundColor = kRGB(0xF7F7F7);
    [contentBg addTopCorner:16];
    [self.view addSubview:contentBg];
    
    [contentBg addSubview:self.categoryV];
    [contentBg addSubview:self.containView];
    
    [self.searchV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(0);
        make.top.mas_equalTo(self.isPush ? kHeightForNaigation : kHeightForStatusBar);
        make.height.mas_equalTo(56);
    }];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.searchV.mas_bottom);
        make.leading.trailing.mas_equalTo(0);
        make.height.mas_equalTo(140);
    }];
    [contentBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.headerView.mas_bottom);
    }];
    [self.categoryV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.mas_equalTo(0);
        make.trailing.mas_equalTo(-100);
        make.height.mas_equalTo(50);
    }];
    [self.containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.categoryV.mas_bottom);
    }];
    
    if ([self isSelef]) {
        [contentBg addSubview:self.manageShop];
        [self.manageShop mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-16);
            make.centerY.mas_equalTo(self.categoryV);
            make.size.mas_equalTo(CGSizeMake(75, 20));
        }];
    }
}

#pragma mark - data
- (BOOL)isSelef {
    return [self.userId isEqualToString:kUserAccount.user.id];
}
- (void)getUserInfoData {
    [NET getUserInfo:self.userId success:^(id  _Nonnull responseObject) {
        self.model = [UserModel mj_objectWithKeyValues:responseObject];
        self.model.isSelf = [self isSelef];
        self.headerView.model = self.model;
        [self updateUserData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)blackData {
    [YPProgressHud showHudInview:self.view];
    [NET blackUser:self.userId type:1 success:^(id  _Nonnull responseObject) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(@"用户已被您拉黑");
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

- (void)reportData {
    [YPProgressHud showHudInview:self.view];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [YPProgressHud hideHudForView:self.view];
        kShowText(@"举报成功,平台将在24小时内进行处理,谢谢反馈");
    });
}

- (void)showFollowStatus:(UserModel *)model {
    if (!model.follow) {
        FollowTipsView *v = [[FollowTipsView alloc] init];
        [v show];
        @weakify(self)
        [v setFollowBlock:^(NSInteger type) {
         @strongify(self)
            [self followUnfollow:model status:type];
        }];
    }else {
        [self followUnfollow:model status:1];
    }
}
- (void)followUnfollow:(UserModel *)model status:(NSInteger)status {
    [YPProgressHud showHudInview:self.view];
    [NET followUser:model.id flag:!model.follow status:status success:^(id  _Nonnull responseObject) {
        self.model.follow = !self.model.follow;
        self.headerView.model = self.model;
        [self removeFollowStatsView];
        [self updateUserData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

- (void)followSetDataWithType:(NSInteger)type {
    [YPProgressHud showHudInview:self.view];
    [NET followSetType:type userId:self.model.id success:^(id  _Nonnull responseObject) {
        kShowText(@"设置完成");
        self.model.upStatus = type == 1 ? YES : NO;
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }]; 
}

#pragma mark - 事件
- (void)moreAction {
    [UIAlertController showActionSheetInViewController:self withTitle:nil message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拉黑",@"举报"] tapBlock:^(UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
        if (buttonIndex == UIAlertControllerBlocksFirstOtherButtonIndex) {
            [self blackData];
        }else if (buttonIndex == UIAlertControllerBlocksFirstOtherButtonIndex + 1) {
            [self reportData];
        }
    }];
}

- (void)updateUserData {
    ShopListController *vc = (ShopListController *)self.containView.validListDict[@(self.categoryV.selectedIndex)];
    vc.model = self.model;
}

- (void)exitManager {
    self.manageShop.selected = NO;
    for (int i = 0; i < self.categoryV.titles.count; i++) {
        ShopListController *vc = (ShopListController *)self.containView.validListDict[@(i)];
        [vc setShopEditing:self.manageShop.selected];
    }
}

- (void)showFollowSetView {
    FollowSetView *setV = [[FollowSetView alloc] init];
    setV.upStatus = self.model.upStatus;
    [setV show];
    @weakify(self)
    [setV setFollowSetBlock:^(NSInteger tag) {
           @strongify(self)
        [self followSetDataWithType:tag];
    }];
}

#pragma mark - 懒加载
- (SearchView *)searchV {
    if (!_searchV) {
        _searchV = [[SearchView alloc] init];
        @weakify(self)
        _searchV.searchBlock = ^(NSString * _Nonnull searchStr) {
         @strongify(self)
            ShopListController *vc = (ShopListController *)self.containView.validListDict[@(self.categoryV.selectedIndex)];
            [vc searchData:searchStr];
        };
        _searchV.qrBlock = ^{
          @strongify(self)
            ScanCodeViewController *vc = [[ScanCodeViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        _searchV.clearBlcok = ^{
            @strongify(self)
            ShopListController *vc =  (ShopListController *)self.containView.validListDict[@(self.categoryV.selectedIndex)];
            [vc searchData:nil];
        };
    }
    return _searchV;
}

- (ShopInfoView *)headerView {
    if (!_headerView) {
        _headerView = [[ShopInfoView alloc] initWithFrame:CGRectMake(0, 0, kWidthForScreen, 140)];
        @weakify(self)
        _headerView.publishGoodsBlock = ^{
         @strongify(self)
            PublishShopViewController *vc = [[PublishShopViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        [_headerView setFollowUserBlock:^(UserModel * _Nonnull model) {
            @strongify(self)
            [self showFollowStatus:model];
        }];
        [_headerView setSetFollowBlock:^(UserModel * _Nonnull model) {
            @strongify(self)
            [self showFollowSetView];
        }];
    }
    return _headerView;
}

- (JXCategoryTitleView *)categoryV {
    if (!_categoryV) {
        _categoryV = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 196, kWidthForScreen, 50)];
        _categoryV.backgroundColor = [UIColor clearColor];
        _categoryV.titles = [self isSelef] ? @[@"上架商品",@"下架商品",@"全部商品"] : @[@"上架商品"];
        _categoryV.averageCellSpacingEnabled = NO;
        _categoryV.contentEdgeInsetLeft = 16;
        _categoryV.delegate = self;
        _categoryV.cellSpacing = 30;
        _categoryV.titleFont = kFontRegula(14);
        _categoryV.titleColor = kRGB(0x999999);
        _categoryV.titleSelectedFont = kFontSemiBold(14);
        _categoryV.titleSelectedColor = kRGB(0x333333);
        _categoryV.titleColorGradientEnabled = YES;
        _categoryV.listContainer = self.containView;
        
        JXCategoryIndicatorBackgroundView *indict = [[JXCategoryIndicatorBackgroundView alloc] init];
        indict.indicatorWidth = 16;
        indict.indicatorHeight = 4;
        indict.indicatorColor = kBgColor;
        indict.indicatorCornerRadius = 2;
        indict.verticalMargin = -15;
        _categoryV.indicators = @[indict];
    }
    return _categoryV;
}
- (JXCategoryListContainerView *)containView {
    if (!_containView) {
        _containView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    }
    return _containView;
}
- (UIButton *)manageShop {
    if (!_manageShop) {
        _manageShop = [UIButton buttonWithType:UIButtonTypeCustom];
        [_manageShop setImage:[UIImage imageNamed:@"icon_shopManage"] forState:UIControlStateNormal];
        [_manageShop setTitle:@"批量管理" forState:UIControlStateNormal];
        [_manageShop setTitle:@"退出管理" forState:UIControlStateSelected];
        [_manageShop setTitleColor:kBgColor forState:UIControlStateNormal];
        _manageShop.titleLabel.font = kFontMediium(14);
        [_manageShop setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 3)];
        @weakify(self)
        [[_manageShop rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self)
            self.manageShop.selected = !self.manageShop.selected;
            for (int i = 0; i < self.categoryV.titles.count; i++) {
                ShopListController *vc = (ShopListController *)self.containView.validListDict[@(i)];
                [vc setShopEditing:self.manageShop.selected];
            }
        }];
    }
    return _manageShop;
}
#pragma mark - 代理

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    [self.containView didClickSelectedItemAtIndex:index];
}
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    ShopListController *vc = [[ShopListController alloc] init];
    vc.enable = (1 - index);
    vc.isMyself = [self isSelef];
    vc.userId = self.userId;
    vc.model = self.model;
    if (self.manageShop.selected) {
        [vc setShopEditing:self.manageShop.selected];
    }
    return vc;
}
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.categoryV.titles.count;
}

@end
